<template>
  <div class='sankey' ref="chartRef"></div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, reactive, Ref, onUnmounted } from 'vue';
import { traverseTree } from './utils'
import { EChartsOption } from 'echarts'
import { useECharts } from '@/hooks/web/useECharts'
import { SankeyChart } from 'echarts/charts';

const props = defineProps({
  sankeyData: {
    type: Object,
    required: true
  }
});

const option: EChartsOption = {
  title: {
    text: ''
  },
  tooltip: {
    trigger: 'item',
    triggerOn: 'mousemove',
  },
  label: {
    show: true,
    formatter: function (params) {
      return params.name + ': ' + (params.data.ratio * 100).toFixed(2) + '%';
    }
  },
  series: [
    {
      type: 'sankey',
      layoutIterations: 0, // 自行根据sort排序
      draggable: true, // 节点可拖动
      emphasis: {
        focus: 'adjacency'
      },
      lineStyle: {
        color: 'source',
        curveness: 0.5
      },
      data: [],
      links: [],
      label: {
        color: 'rgba(0,0,0,0.7)',
        fontFamily: 'Arial',
        fontSize: 10,
      },
      top: 20,
      bottom: 20
    }
  ]
};

watch(
  () => props.sankeyData,
  (newVal) => {
    setData(newVal);
  },
  { deep: true }
);
let resizeObserver: ResizeObserver | null = null
const chartRef = ref<HTMLDivElement | null>(null)
const { setOptions, echarts, resize, getInstance } = useECharts(chartRef as Ref<HTMLDivElement>)
echarts.use([SankeyChart])
const setData = (data) => {
  const realData = traverseTree(data);
  console.log(realData);
  setOptions({
    title: {
      text: data.classifyName
    },
    ...option,
    series: {
      ...option.series![0],
      data: realData.data,
      links: realData.links
    }
  });
}

onMounted(() => {
  props.sankeyData && setData(props.sankeyData)
  resizeObserver = new ResizeObserver(() => {
    resize()
  })
  if (chartRef.value) {
    resizeObserver.observe(chartRef.value as HTMLDivElement)
  }
})

onUnmounted(() => {
  if (resizeObserver && chartRef.value) {
    resizeObserver.unobserve(chartRef.value as HTMLDivElement)
  }
})

</script>

<style scoped>
/* Add any styles you need here */
.sankey {
  width: 100%;
  height: 100%;
}
</style>
